<?php 
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

defined('THINK_PATH') or exit();

class SessionDb
{
	protected $lifeTime      = ''; 
	protected $sessionTable  = '';
	protected $hander;

	public function open($savePath, $sessName)
	{ 
		$this->lifeTime = C('SESSION_EXPIRE')?C('SESSION_EXPIRE'):ini_get('session.gc_maxlifetime');
		$this->sessionTable  =   C('SESSION_TABLE')?C('SESSION_TABLE'):C("DB_PREFIX")."session";
		$hander  = mysqli_connect(C('DB_HOST'),C('DB_USER'),C('DB_PWD'), C('DB_NAME'), C('DB_PORT')) or die('Unale to connect');
		if(!$hander) 
		return false; 
		$this->hander = $hander;
	} 

	public function close()
	{ 
		$this->gc(ini_get('session.gc_maxlifetime')); 
		return mysqli_close($this->hander); 
	} 

	public function read($sessID)
	{
		$res = mysqli_query($this->hander,"SELECT session_data AS data FROM ".$this->sessionTable." WHERE session_id = '$sessID'   AND session_expire >".time());
		if($res) {
		$row = mysqli_fetch_assoc($res);
		return $row['data']; 
		}
		return ""; 
	} 

	public function write($sessID,$sessData)
	{ 
		$expire = time() + $this->lifeTime; 
		$sql = "REPLACE INTO  ".$this->sessionTable." (  session_id, session_expire, session_data)  VALUES( '$sessID', '$expire',  '$sessData')";
		mysqli_query($this->hander,$sql);
		return true;
	} 

	public function destroy($sessID)
	{
		mysqli_query($this->hander,"DELETE FROM ".$this->sessionTable." WHERE session_id = '$sessID'");
		return true; 
	}

	public function gc($sessMaxLifeTime)
	{ 
		mysqli_query("DELETE FROM ".$this->sessionTable." WHERE session_expire < ".time(),$this->hander); 
		return mysqli_affected_rows($this->hander); 
	}

	public function execute()
	{
		session_set_save_handler(
			array(&$this,"open"),
			array(&$this,"close"),
			array(&$this,"read"),
			array(&$this,"write"),
			array(&$this,"destroy"),
			array(&$this,"gc")
		);
	}
}